"""
MEMESA-TOOLS
============
Model preparation, vertex enumeration and vertex analysis tools developed as
part of the MEMESA project. 

    Copyright (C) 2009-2012 Brett G. Olivier and Steven M. Kelk

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Author: Brett G. Olivier
Contact email: bgoli@users.sourceforge.net

"""

# Set userdata here #

# iJR904
work_dir = 'iJR904'
model_file = 'Ecoli_iJR904.l3.xml'

# End userdata #


### Active script ###

import os, time, numpy
cDir = os.path.dirname(os.path.abspath(os.sys.argv[0]))
model_name = model_file
model_dir = os.path.join(cDir, work_dir, 'sbml')
work_dir = os.path.join(cDir, work_dir, 'init_model')

from pyscescbm.CBVersion import __DEBUG__, __version__
from pyscescbm import CBRead, CBWrite, CBTools
from pyscescbm import CBSolver as slv

work_dir = os.path.join(cDir, work_dir)
if not os.path.exists(work_dir):
    os.mkdir(work_dir)

mod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)
mod.id = model_name

CBTools.processBiGGchemFormula(mod)
CBTools.processSBMLAnnotationNotes(mod, annotation_key='note')

slv.analyzeModel(mod, lpFname=os.path.join(work_dir, 'raw_(%s)' % mod.id))

# scan for duplicates
print '\nScan for duplicates'
dup_C = CBTools.scanForReactionDuplicates(mod, ignore_coefficients=False)
##  print 'Reactions with matching reagents: %s\n' % len(dup_noC) 
print '\nReaction pairs with matching reagents and coefficients: %s' % len(dup_C)
for d in dup_C:
    print('%s == %s (%s)' % (d[0],d[1],d[2]))
    
# write duplicate reactions to file
F = file(os.path.join(work_dir,'%s.duplicates.csv' % model_file),'w')
F.write('Model file: %s,,,,\n' % model_file)
F.write('Duplicate reactions pairs: %s,,,,\n' % len(dup_C))
for d in dup_C:
    F.write('\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % (d[0],d[1],d[2],d[3],d[4]))
F.write('\n')
F.close()
